package com.spring.boot.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spring.boot.entity.Obj;
import com.spring.boot.entity.SysMenu;
import com.spring.boot.entity.SysRole;
import com.spring.boot.entity.SysRoleMenu;
import com.spring.boot.mapper.SysMenuMapper;
import com.spring.boot.mapper.SysRoleMapper;
import com.spring.boot.service.SysMenuService;
import com.spring.boot.service.SysRoleMenuService;
import com.spring.boot.service.SysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("sysRoleServiceImpl")
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {

    @Autowired
    private SysRoleMapper roleMapper;
    @Autowired
    private SysRoleMenuService roleMenuService;
    @Autowired
    private SysMenuService menuService;

    @Override
    public SysRole mySave(SysRole role) {
        String menus = role.getMenu();
        String[] menuArr = menus.split(",");
        StringBuilder newMenus = new StringBuilder();
        for (String menu : menuArr) {
            if (!StrUtil.isEmpty(menu)){
                SysMenu sysMenu = menuService.getOne(new QueryWrapper<SysMenu>().eq("menu", menu));
                int menuId = sysMenu.getId();
                newMenus.append(menuId).append(',');
            }
        }
        role.setMenu(newMenus.toString());
        roleMapper.insert(role);
        //需要的参数：1.role id  2.menu id
        saveRoleMenu(role.getId(),newMenus.toString());
        return role;
    }

    private void saveRoleMenu(int roleId,String menuIds){
        //拆分menuIds成数组
        String[] menuIdArr = menuIds.split(",");//是不是可以把这个字符串数组转成整型数组？
        for (String menuId : menuIdArr) {
            roleMenuService.save(new SysRoleMenu(roleId, menuId));
        }
    }
}
